package com.tarena.luban.demo.gateway.filters;

import com.alibaba.nacos.common.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

@Slf4j
@Component
public class MyFilter01 implements GlobalFilter, Ordered {
    /**
     * 只要过滤器在网关生效,所有请求都会经过这个方法
     * @param exchange 包含请求和响应对象
     * @param chain 过滤器所在的过滤链
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("请求经过了MyFilter01...");
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        RequestPath path = request.getPath();
        log.info("请求路径path:{}",path); // /hello
        // 获取全路径地址 url
        URI uri = request.getURI();
        log.info("请求url全路径:{}",uri); // http://localhost:10000/hello?name=Tom
        // 获取请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        log.info("请求参数queryParams:{}",queryParams);
        List<String> names = queryParams.get("name");
        List<String> ages = queryParams.get("age");
        if(CollectionUtils.isNotEmpty(names)){
            log.info("请求参数names:{}",names);
        }
        if(CollectionUtils.isNotEmpty(ages)){
            log.info("请求参数ages:{}",ages);
        }
        // 获取请求头数据
        HttpHeaders headers = request.getHeaders();
        // 获取Accept的请求头信息
        // 方式一
        List<MediaType> accept = headers.getAccept();
        log.info("获取accept请求头:{}",accept);
        // 方式二
        List<String> acceptStr = headers.get("Accept");
        log.info("获取acceptStr请求头:{}",acceptStr);

        // 获取Cookie信息
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> location = cookies.get("location");
        if(CollectionUtils.isNotEmpty(location)){
            log.info("获取cookie中location:{}",location);
        }

        // 客户端地址
        String address = request.getRemoteAddress().getAddress().toString();
        log.info("获取客户端address:{}",address);


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}



